package com.fumihiko.modules.sys.oauth2;

import com.fumihiko.common.utils.DateTimeUtil;
import com.fumihiko.common.utils.SxConstants;
import com.fumihiko.modules.ca.service.UserTokenService;
import com.fumihiko.modules.ca.vo.UserTokenVo;
import com.fumihiko.modules.sys.entity.SysUserEntity;
import com.fumihiko.modules.sys.entity.SysUserTokenEntity;
import com.fumihiko.modules.sys.service.ShiroService;
import com.fumihiko.modules.wsbj.entity.TbTokenEntity;
import com.fumihiko.modules.wsbj.service.TbTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 认证
 *
 * @author devilzwy@gmail.com
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;

    @Autowired
    private TbTokenService tbTokenService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
        //Long userId = user.getUserId();
        Long userId = 1L;

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        //根据accessToken，查询用户信息
        //非单点登录token
        //SysUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken);
        //单点登录token
       TbTokenEntity tbTokenEntity = tbTokenService.getUserTokenVoObjByAccessToken(accessToken);
          //非单点登录token
//        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
//             throw new IncorrectCredentialsException("token失效，请重新登录");
//        }
        //单点登录判断token是否为空
        if(tbTokenEntity == null)
        {
            Cookie cookie = new Cookie("token",null);
            cookie.setMaxAge(0); //设置立即删除
            response.addCookie(cookie);

            throw new IncorrectCredentialsException("token为空，请重新登录");
        }

         //单点登录token
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long sec = DateTimeUtil.getTimeMinusToSec(DateTimeUtil.getCurrentTime(), formatter.format(tbTokenEntity.getExpirationTime()));
        if(sec > 0){
            Cookie cookie = new Cookie("token",null);
            cookie.setMaxAge(0); //设置立即删除
            response.addCookie(cookie);

            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
//非单点登录token用户
        //查询用户信息
//        SysUserEntity user = shiroService.queryUser(tokenEntity.getUserId());
//        //账号锁定
//        if(user.getStatus() == 0){
//            throw new LockedAccountException("账号已被锁定,请联系管理员");
//        }
        //单点登录用户
        SysUserEntity user = new SysUserEntity();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
